﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainForm.cs" company="">
//   
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace AdminTool
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using System.Windows.Forms;

    using ExecutionTool.Profile;

    public partial class MainForm : Form
    {
        #region Fields

        private readonly Dictionary<string, IProfileConfigurator> configControls = new Dictionary<string, IProfileConfigurator>();

        private bool profileDataLoaded;

        #endregion

        #region Constructors and Destructors

        public MainForm()
        {
            this.InitializeComponent();
        }

        #endregion

        #region Methods

        private void BuildConfigControls()
        {
            var nodeNames = typeof(NodeName).GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

            foreach (var info in nodeNames)
            {
                var nodeName = info.Name;
                var controlName = nodeName.Replace("Node", "Config");
                var controlType = Type.GetType("AdminTool." + controlName);

                if (controlType == null)
                {
                    throw new Exception("Unknown type. [" + controlName + "]");
                }

                this.configControls.Add(info.Name, (IProfileConfigurator)Activator.CreateInstance(controlType));
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.treeView1.ExpandAll();
            this.treeView1.AfterSelect += (o, args) =>
                {
                    ////MessageBox.Show(args.Action + ":" + args.Node.Name);
                    this.panel1.Controls.Clear();
                    this.panel1.Controls.Add((UserControl)this.configControls[args.Node.Name]);
                };

            this.BuildConfigControls();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var assembly = Assembly.GetExecutingAssembly();

            MessageBox.Show(string.Format("SQL Azure Data Protector, Admin Tool ({0})", assembly.GetName().Version), "About");
        }

        private void encDecToolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new EncDec();
            f.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void loadProfileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var profiles = ProfileFacade.LoadProfiles();

            if (profiles.Count > 0)
            {
                var p = profiles[0];
                foreach (var pair in this.configControls)
                {
                    pair.Value.LoadProfile(p);
                }

                this.textBoxProfileName.Text = p.Name;
                this.textBoxProfileDescription.Text = p.Description;
                this.textBoxRecipients.Text = p.Orchestration.NotificationList;
                this.numericUpDownDaysToKeep.Value = p.Orchestration.DaysToKeep;

                this.textBoxProfileName.ReadOnly = true;
            }

            this.profileDataLoaded = true;
            this.toolStripStatusLabelStatus.Text = "Profile data loaded.";
        }

        private void saveProfileDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.profileDataLoaded)
            {
                if (ProfileFacade.ProfileDataExists())
                {
                    MessageBox.Show("Existing profile data detected. Please load and edit profile data instead.", "Conflict");
                    return;
                }
            }

            var profile = new Profile
                {
                    Orchestration = new Orchestration(), 
                    Name = this.textBoxProfileName.Text.Trim(), 
                    Description = this.textBoxProfileDescription.Text.Trim(), 
                    Source = new SqlAzureLocation(), 
                    TargetAzureStorage = new AzureStorageLocation(), 
                    TargetSqlAzureVerification = new SqlAzureLocation(), 
                    TargetOnPremisesLocation = new OnPremisesLocation(), 
                };
            profile.Orchestration.NotificationList = this.textBoxRecipients.Text.Trim();
            profile.Orchestration.DaysToKeep = Convert.ToInt32(this.numericUpDownDaysToKeep.Value);

            foreach (var pair in this.configControls)
            {
                pair.Value.SaveProfile(profile);
            }

            ProfileFacade.SaveProfiles(new List<Profile> { profile });
            this.toolStripStatusLabelStatus.Text = "Profile data saved.";
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }

        private void usageDocToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var p = new Process { StartInfo = { FileName = @"SQL Azure Data Protector.docx", WindowStyle = ProcessWindowStyle.Maximized } };
            p.Start();
        }

        #endregion

        private sealed class NodeName
        {
            #region Constants

            internal const string NodeCopyDatabase = "NodeCopyDatabase";

            internal const string NodeCopyToOnPremises = "NodeCopyToOnPremises";

            internal const string NodeExport = "NodeExport";

            internal const string NodeSource = "NodeSource";

            internal const string NodeVerify = "NodeVerify";

            #endregion
        }
    }
}
